package com.shigen.springcloud.service;

import cn.hutool.core.util.IdUtil;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import java.util.concurrent.TimeUnit;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PathVariable;

@Service
public class PaymentService {

  public String payment_OK(Integer id) {
    return "线程池： " + Thread.currentThread().getName() + "payment_OK, id = " + id;
  }

  @HystrixCommand(fallbackMethod = "payment_TimeOutHandler", commandProperties = {
      @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds", value = "3000")
  })
  public String payment_TimeOut(Integer id) {
    int timeout = 5;
    try {
      TimeUnit.SECONDS.sleep(timeout);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
    return "线程池： " + Thread.currentThread().getName() + "payment_TimeOut, id = " + id;
  }

  public String payment_TimeOutHandler(Integer id) {
    return "payment_TimeOutHandler.....系统繁忙，稍后重试";
  }

  //服务熔断
  @HystrixCommand(fallbackMethod = "paymentCircuitBreaker_fallback", commandProperties = {
      @HystrixProperty(name = "circuitBreaker.enabled", value = "true"),  //是否开启断路器
      @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold", value = "10"),   //请求次数超过了峰值，熔断器将会关闭
      @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds", value = "10000"),  //时间范围
      @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage", value = "60"), //失败率达到多少后跳闸
  })
  public String paymentCircuitBreaker(Integer id) {
    if (id < 0) {
      throw new RuntimeException("*****id 不能负数");
    }
    String serialNumber = IdUtil.simpleUUID();
    return Thread.currentThread().getName() + "\t" + "调用成功,流水号：" + serialNumber;
  }

  public String paymentCircuitBreaker_fallback(@PathVariable("id") Integer id) {
    return "id 不能负数，请稍候再试,(┬＿┬)/~~     id: " + id;
  }
}
